// order.js
Page({
  data: {
    statusBarHeight: 0,
    showAddressPopup: false,
    selectedAddress: null,
    addressList: [],
    orderItems: [],
    totalPrice: 0,
    remark: null,
    orderId: 0
  },

  onLoad: function (options) {
    const windowInfo = wx.getWindowInfo()
    this.setData({
      statusBarHeight: windowInfo.statusBarHeight
    })
    const selectedItems = wx.getStorageSync('selectedItems') || [];
    console.log(selectedItems);
    this.processOrderData(selectedItems);
    this.getAddressList();
    this.loadOrderItems();
  },

  // 获取地址列表
  getAddressList() {
    wx.showLoading({ title: '加载中...' })
    const app = getApp();
    const token = app.globalData.userInfo.token;
    const userId = app.globalData.userInfo.id;
    wx.request({
      url: 'http://localhost:8080/manage/address/list',
      method: 'GET',
      data : { userId},
      success: (res) => {
        wx.hideLoading()
        if (res.statusCode === 200 && res.data.code === 200) {
          const addressList = res.data.rows.map(item => ({
            ...item,
            fullAddress: `${item.provinceName}${item.cityName}${item.districtName}${item.detail}`
          }))
          
          this.setData({
            addressList,
            selectedAddress: addressList[0] || null
          })
        } else {
          wx.showToast({
            title: res.data.msg || '获取地址失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        wx.hideLoading()
        wx.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
      }
    })
  },

  // 选择地址
  selectAddress(e) {
    const selectedAddress = e.currentTarget.dataset.address
    this.setData({
      selectedAddress,
      showAddressPopup: false
    })
  },

  // 打开地址弹窗
  chooseAddress() {
    this.setData({ showAddressPopup: true })
  },

  // 关闭弹窗
  closeAddressPopup() {
    this.setData({ showAddressPopup: false })
  },

  // 新增地址
  addAddress() {
    wx.navigateTo({
      url: '/pages/address-add/address-add'
    })
  },

  // 编辑地址
  editAddress(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/address-edit/address-edit?addressId=${id}`
    })
  },
  onInputRemark: function (e) {
    this.data.remark=e.detail.value;
  },
  // 返回
  onBack() {
    wx.navigateBack()
  },

  // 阻止冒泡
  stopPropagation() {},

  loadOrderItems: function() {
    const selectedItems = wx.getStorageSync('selectedItems') || [];
    this.processOrderData(selectedItems);
  },

  processOrderData: function(items) {
    const totalPrice = items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
    const totalQuantity = items.reduce((sum, item) => sum + item.quantity, 0);
    
    this.setData({
      orderItems: items,
      totalPrice,
      totalQuantity
    });
  },

  submitOrder() {
    // 校验地址
    if (!this.data.selectedAddress) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      })
      return
    }
    wx.showLoading({ title: '提交中...' })
    const d = new Date();
    const orderTime = [
      d.getFullYear(),
      (d.getMonth()+1).toString().padStart(2,'0'),
      d.getDate().toString().padStart(2,'0'),
      d.getHours().toString().padStart(2,'0'),
      d.getMinutes().toString().padStart(2,'0'),
      d.getSeconds().toString().padStart(2,'0')
    ].join('');
    const randomNum = Math.floor(Math.random() * 100);
    const userId = getApp().globalData.userInfo.id;
    const number = [
      orderTime,
      userId.toString().padStart(4,'0'),
      randomNum.toString().padStart(4,'0')
    ].join('');
    wx.request({
      url: 'http://localhost:8080/manage/orders',
      method: 'POST',
      data : { 
        number,
        status : 1,
        userId,
        addressId : this.data.selectedAddress.id,
        orderTime : d,
        remark : this.data.remark,
        amount : this.data.totalPrice
      },
      success: (res) => {
        const selectedItems = wx.getStorageSync('selectedItems');
        this.getByOrderId(number, () => {
          // 此回调在orderId设置后执行
          selectedItems.forEach(dish => {
            this.addOrderDetail(dish);
            this.deleteCart(dish.id);
          });
          wx.navigateBack();
        });
      }
    })
  },
  addOrderDetail: function (dish) {
    wx.request({
      url: 'http://localhost:8080/manage/detail',
      method: 'POST',
      data : { 
        name : dish.name,
        image : dish.image,
        orderId : this.data.orderId,
        dishId : dish.id,
        number : dish.quantity,
        amount : dish.price
      }
    })
  },

  getByOrderId: function (number,callback) {
    wx.request({
      url: 'http://localhost:8080/manage/orders/list',
      method: 'GET',
      data : { 
        number
      },
      success: (res) => {
        this.setData({ orderId: res.data.rows[0].id }, () => {
          callback(); // 数据更新后执行回调
        });
      }
    })
  },
  deleteCart: function (cartItemId) {
    wx.request({
      url: `http://localhost:8080/manage/cart/${cartItemId}`,
      method: 'DELETE'
    })
  }
})